<template>
  <div class="chat-container">
    <div>
      <!-- 顶部样式 -->
      <ChatNavtab />
      <!-- 聊天对话框 -->
      <BubbleList
        :key="bubbleListKey"
        ref="bubbleListRef"
        :list="agentChatStore.conversationHistory"
        class="BubbleListClass border-b-[1px] border-l-[1px] border-r-[1px] border-[#e5e5e5] p-4"
        max-height="1000px"
      >
        <!-- 自定义聊天气泡底部 -->
        <template #footer="{ item }">
          <BubbleFooter :key="item.id" :item="item" />
        </template>
        <template #content="{ item }">
          <div v-if="item?.image && item.image.length > 0">
            <el-image
              :initial-index="4"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="item.image"
              :src="item.image[0]"
              :zoom-rate="1.2"
              fit="cover"
              show-progress
              style="width: 100px; height: 100px"
            />
          </div>
          <div>
            {{ item.placement === 'end' ? item.content : item.trans }}
          </div>
        </template>
      </BubbleList>
    </div>
    <!-- 发送输入框 -->
    <Sender
      ref="senderRef"
      v-model:model-value="message"
      :auto-size="{ minRows: 2, maxRows: 5 }"
      class="sender-container mt-4"
      variant="updown"
      @submit="sendMessage"
    >
      <!-- 自定义头部 -->
      <template #header>
        <SenderHeader v-model="files" />
        <div class="px-4 py-2">
          <FosoEmoji @select-emoji="handleSelectEmoji" />
        </div>
      </template>
      <!-- 自定义前缀 -->
      <template #prefix>
        <SenderPrefix v-model="files" v-model:translate-text="message" />
      </template>
      <template #footer> </template>
    </Sender>
  </div>
</template>
<script setup lang="ts">
import type { BubbleListProps } from 'vue-element-plus-x/types/BubbleList';

import type { SelfFilesCardProps } from '../type';

import { nextTick, onMounted, ref, watch } from 'vue';

import { $t } from '@vben/locales';
import { useAccessStore } from '@vben/stores';

import { useIntersectionObserver, useScroll } from '@vueuse/core';

import { getConversationHistory } from '#/api/agent/conversation';
import { UseWebSocket } from '#/api/websocket';
import { type listType, useAgentChatStore } from '#/store';
import { base64encryption } from '#/utils/base64decode';
import { useProvideCounter } from '#/utils/chatInjectionState';

import { BubbleListItemHandle } from './bubbleConfig';
import { BubbleFooter, ChatNavtab, SenderHeader, SenderPrefix } from './index';

// 定义组件事件
const emit = defineEmits<{
  // 会话数据置顶操作
  triggerDataTop: [data?: any];
}>();
const accessStore = useAccessStore();
// 连接websocket
const { send } = UseWebSocket(
  `${import.meta.env.VITE_WS_URL}?token=${accessStore.accessToken}`,
);

// 用于强制重新渲染的 key
const bubbleListKey = ref(0);
// 消息气泡容器
const targetElements = ref<HTMLElement[]>([]);
// 获取会话组件实例
const bubbleListRef = useTemplateRef('bubbleListRef');
// 注入组件变量状态
useProvideCounter(bubbleListRef);

// 监听聊天框的滚动条的变化
const { y } = useScroll(bubbleListRef);

// 用于手动暂停/恢复所有观察器
const observers = ref<Array<{ pause: () => void; resume: () => void }>>([]);
// 示例调用
const agentChatStore = useAgentChatStore();
// 文件数组
const files = ref<SelfFilesCardProps[]>([]);
const message = ref(''); // 消息
const readedIds = ref<string[]>([]); // 获取未读消息ID

// 获取输入框实例
const senderRef = ref();

// 发送消息
const sendMessage = () => {
  if (
    agentChatStore.customerId === undefined ||
    agentChatStore.customerId === ''
  ) {
    ElMessage.error('请先选择客户会话！');
    message.value = '';
    return;
  }
  bubbleListRef.value?.scrollToBottom();
  // 数据加码
  const encodeddata = base64encryption({
    agentId: agentChatStore.agentId,
    customerId: agentChatStore.customerId,
    msgInfo: {
      id: 0,
      conType: 1,
      contJson: {
        text: {
          previewUrl: false,
          body: message.value,
        },
        image: {
          link: files.value.map((item) => item.name),
        },
      },
    },
  });
  send(
    JSON.stringify({
      type: 'conversation',
      action: 'sendMsg',
      data: encodeddata, // 转为base64格式
    }),
  );

  // 发送消息后触发dataTop方法
  emit('triggerDataTop', agentChatStore.customerId);
  message.value = '';
  files.value = [];
  // 让输入框失去焦点
  nextTick(() => {
    senderRef.value?.blur();
  });
};

// 发送请求获取会话历史
const GetConversationHistory = async () => {
  // if (agentChatStore.conversationHistory[0]?.id) {
  const res = await getConversationHistory({
    page: 1,
    pageSize: 2,
    lastId: agentChatStore.conversationHistory[0]?.id,
    agentId: agentChatStore.agentId,
    customerId: agentChatStore.customerId,
    conversationId: '1',
  });
  // 设置是否有更多数据
  agentChatStore.setHasMoreData(res.hasMoreData);
  // 设置会话数据
  agentChatStore.pushHistoryConversation(res.data);
  // 获取新的数据后，让滚动条自动下降点距离
  bubbleListRef.value.scrollToBubble(1);
};

// 表情选择器
const handleSelectEmoji = (emoji: any) => {
  message.value += emoji.name;
};

onMounted(async () => {
  senderRef.value?.openHeader();
});

// 监听滚动，但仅在初始化后触发
watch(
  () => y.value,
  (newY) => {
    // 没有更多数据，直接返回
    if (!agentChatStore.hasMoreData && newY === 0) {
      ElMessage.info($t('customer.chat.nodata'));
      return;
    }

    // 如果滚动到顶部（y.value === 0）且已有足够的历史记录
    if (newY === 0 && agentChatStore.conversationHistory.length >= 10) {
      ElMessage.success($t('customer.chat.loadmoredata'));
      GetConversationHistory();
    }
  },
);

// 监听客户ID变化，自动滚动到底部
watch(
  () => agentChatStore.customerId,
  async (newCustomerId, oldCustomerId) => {
    // 只有在客户ID真正变化时才滚动
    if (newCustomerId && newCustomerId !== oldCustomerId) {
      // 获取会话历史数据
      const res = await getConversationHistory({
        page: 1,
        pageSize: 10,
        agentId: agentChatStore.agentId,
        customerId: newCustomerId,
        conversationId: '1',
      });
      // 处理消息格式
      const newdata = BubbleListItemHandle(res.data);
      agentChatStore.setHasMoreData(res.hasMoreData);
      // 设置仓库会话数据
      agentChatStore.setConversationList(newdata);
      // 重新渲染会话组件
      bubbleListKey.value++;
    }
  },
);

// 监听会话未读消息设置已读消息
watch(
  () => agentChatStore.conversationHistory,
  (newvalue: BubbleListProps<listType>['list']) => {
    if (newvalue.length > 0) {
      // 清理之前的观察器
      observers.value.forEach((observer) => {
        observer.pause();
      });
      observers.value = [];
      readedIds.value = [];

      // 等待DOM更新后再获取元素
      nextTick(() => {
        targetElements.value = [
          ...document.querySelectorAll('.el-bubble'),
        ] as HTMLElement[];

        // 为每个目标元素创建观察器
        targetElements.value.forEach((target, index) => {
          const observer = useIntersectionObserver(
            target,
            ([entry]) => {
              // 获取客户未读消息并设置已读
              if (
                entry?.isIntersecting &&
                agentChatStore.conversationHistory[index]?.placement ===
                  'start' &&
                agentChatStore.conversationHistory[index].readedAt === 0
              ) {
                const id = agentChatStore.conversationHistory[index]
                  ?.id as string;
                send(
                  JSON.stringify({
                    type: 'conversation',
                    action: 'sendReadMsg',
                    data: base64encryption({
                      agentId: agentChatStore.agentId,
                      customerId: agentChatStore.customerId,
                      readInfo: {
                        msgId: [id],
                      },
                    }),
                  }),
                );
                agentChatStore.setNoReadCount();
              }
            },
            { root: document.querySelector('.el-bubble-list') as HTMLElement }, // 监听所在的容器
          );
          // 放入监听器中
          observers.value.push(observer);
        });
        // 重置未读数量
        agentChatStore.resetNoReadCount();
      });
    }
  },
);

defineExpose({
  scrollToBottom: () => bubbleListRef.value?.scrollToBottom(),
});
</script>

<style scoped lang="scss">
//屏幕处于小屏幕时，聊天框高度为300px
@media (max-width: 768px) {
  .BubbleListClass {
    height: 300px !important;
  }
}

.BubbleListClass {
  height: 830px;
}

::v-deep(.el-bubble-content) {
  padding-bottom: 100px;
  background-color: var(--el-fill-color) !important;
}

/* 禁用浏览器滚动位置缓存 */
.el-bubble-list {
  scroll-behavior: auto !important;
  -webkit-overflow-scrolling: touch;
}

//会话背景图片设置
.chat-container {
  // background: url('https://n.sinaimg.cn/sinakd20110/285/w1605h1080/20240330/2134-13c9a61ba3f6821071631bfa22cb3d4e.jpg') !important;
  background: url('https://pub-d870eba60fc449308ecc6b4292ce026c.r2.dev/conversation/39f46b4b-8876-4163-a60e-4c3297705753.webp') !important;
  background-repeat: no-repeat !important;
  background-size: 100% 100% !important; /* 关键修改 */
  border-radius: 10px;
}

:deep(.el-bubble-content) {
  color: black !important;
  background-color: #e1ffc7 !important;
}

//取消左侧消息边框样式
:deep(.el-bubble-content-wrapper .el-bubble-content-outlined) {
  border: none !important;
}

// :deep(.el-sender) {
//   border: none !important;
// }

:deep(.el-sender-content .el-textarea__inner) {
  color: black !important;
}
</style>
